<template>
  <div class="body-box">
    <div class="search">
      <a-input-search
        v-model="search"
        class="user-search"
        placeholder="输入搜索内容"
        allow-clear
        @clear="searchData"
        @search="searchData"
        @press-enter="searchData"
      />
    </div>
    <div class="breadcrumb-box">
      <a-breadcrumb>
        <template v-for="(item, index) in breadcrumbDeptList" :key="item.id">
          <a-breadcrumb-item>
            <template #separator>
              <icon-right />
            </template>
            <span
              class="dept-label"
              @click="breadcrumbChange(item.id, index, item)"
              >{{ item.name }}</span
            >
          </a-breadcrumb-item>
        </template>
      </a-breadcrumb>
    </div>
    <a-spin class="spin-box" :loading="loading" tip="加载中...">
      <div class="dept-item-box">
        <template v-for="item in selectableDeptList" :key="item.id">
          <div
            class="item"
            :class="item.checked ? 'check' : ''"
            @click="deptChecked(item.id)"
          >
            <div class="left">
              <div class="dept-icon">
                <img src="./assets/dept.svg" alt="" srcset="" />
              </div>
              <div class="label-text">
                <span>{{ item.name }}</span>
                <span v-if="item.userCount" class="user-num"
                  >({{ item.userCount }})</span
                >
              </div>
            </div>
            <div class="opt" @click="getuserAndDept(item)">下级</div>
          </div>
        </template>
      </div>
      <div v-if="props.type === 'user'" class="user-item-box">
        <template v-for="item in userOfCurrentDept" :key="item.id">
          <div
            class="item"
            :class="item.checked ? 'check' : ''"
            @click="userChecked(item.id)"
          >
            <div class="user-icon" :style="getHeadIconStyle(item.username)">
              {{ getLastName(item.username) }}
            </div>
            <div class="label-text">{{ item.username }}</div>
          </div>
        </template>
      </div>
    </a-spin>
  </div>
</template>

<!--新script-->
<script lang="ts" setup>
  import { defineProps, Ref, ref, onMounted } from 'vue';
  import { cloneDeep } from 'lodash';
  import { queryDeptRecordTreeList } from '@/api/system/dept';
  import { queryUserRecordList } from '@/api/system/user';
  import { UserRecord } from '@/api/system/model/userModel';

  interface Dept {
    name: string;
    code: string;
    id: string;
    checked?: boolean;
    children?: Array<Dept>;
    /** 该部门下人员数量 */
    userCount?: number;
  }
  interface User extends UserRecord {
    checked: boolean;
  }

  const emit = defineEmits(['update:visible', 'update:user']);
  const props = defineProps({
    user: {
      type: Object,
      default: () => {
        return {};
      },
    },
    type: {
      type: String,
      default: 'user',
    },
    rootDeptName: {
      type: String,
      default: '',
    },
  });
  const headColors: Array<{
    /** 头像字颜色 */
    color: string;
    /** 头像字背景颜色 */
    backgroundColor: string;
  }> = [
    {
      color: '#722ED1',
      backgroundColor: '#F5E8FF',
    },
    {
      color: '#13C2C2',
      backgroundColor: '#E6FFFB',
    },
    {
      color: '#FF9A01',
      backgroundColor: '#FFFAE8',
    },
    {
      color: '#2F54EB',
      backgroundColor: '#F0F5FF',
    },
  ];
  const search = ref('');
  const loading = ref(false);
  /** 部门可选数据 */
  const selectableDeptList: Ref<Dept[]> = ref([]);
  /** 指定部门下的可选人员数据 */
  const userOfCurrentDept: Ref<Array<User>> = ref([]);
  /** 部门备份 */
  const selectableDeptLisBack: Ref<Dept[]> = ref([]);
  /** 可选人员备份 */
  const userOfCurrentDeptBack: Ref<Array<User>> = ref([]);
  // 面包屑导航数据
  const breadcrumbDeptList: Ref<Array<Dept>> = ref([]);
  // 根节点
  const rootDept: Ref<Dept> = ref({
    id: '0',
    code: '0',
    name: props.rootDeptName || '根部门',
    userCount: 0,
  });
  // 当前部门
  const currentDeptId = ref('0');
  breadcrumbDeptList.value.push(rootDept.value);
  onMounted(() => {
    getData('');
  });
  // 获取hash
  function getHashCode(str: string) {
    let hash = 1315423911;
    let i;
    let ch;
    // eslint-disable-next-line no-plusplus
    for (i = str.length - 1; i >= 0; i--) {
      ch = str.charCodeAt(i);
      // eslint-disable-next-line no-bitwise
      hash ^= (hash << 5) + ch + (hash >> 2);
    }
    // eslint-disable-next-line no-bitwise
    return hash & 0x7fffffff;
  }
  // 获取文件颜色
  const getHeadIconStyle = (name: any) => {
    const hash = getHashCode(getLastName(name));
    const style = headColors[hash % headColors.length];
    return style;
  };
  // 获取名字最后一个字
  const getLastName = (name: any) => {
    return name.charAt(name.length - 1);
  };
  // 面包屑点击
  const breadcrumbChange = (id: string, i: number, item: any) => {
    search.value = '';
    if (i === 0) {
      breadcrumbDeptList.value.length = 0;
      breadcrumbDeptList.value.push(rootDept.value);
      getData(id);
    } else {
      breadcrumbDeptList.value = breadcrumbDeptList.value.slice(0, i + 1);
      getuserAndDept(item, true);
    }
  };
  // 获取部门和用户
  const getuserAndDept = async (item: any, handleIsNext = false) => {
    // if (currentDeptId.value !== item.id) {
    if (!handleIsNext) {
      breadcrumbDeptList.value.push(item);
    }
    selectableDeptList.value.length = 0;
    userOfCurrentDept.value.length = 0;
    if (item.children?.length > 0) {
      selectableDeptList.value = [...item.children];
    }
    loading.value = true;
    const params = {
      deptCode: item.code,
      page: 1,
      limit: 10000,
    };
    const res1: any = await queryUserRecordList(params);
    userOfCurrentDept.value.push(...res1.data.list);
    loading.value = false;
    // }
    currentDeptId.value = item.id;
  };
  // 后端返回数据
  const getData = async () => {
    loading.value = true;
    selectableDeptList.value.length = 0;
    userOfCurrentDept.value.length = 0;
    const res = await queryDeptRecordTreeList({});
    selectableDeptList.value = [...res.data];
    loading.value = false;
    selectableDeptLisBack.value = cloneDeep(selectableDeptList.value);
    userOfCurrentDeptBack.value = cloneDeep(userOfCurrentDept.value);
  };
  // 查询数据
  const searchData = () => {
    if (search.value) {
      selectableDeptList.value = selectableDeptList.value.filter((e: any) => {
        return e.name.includes(search.value);
      });
      userOfCurrentDept.value = userOfCurrentDept.value.filter((e: any) => {
        return e.username.indexOf(search.value) > -1;
      });
    } else {
      userOfCurrentDept.value = userOfCurrentDeptBack.value;
      selectableDeptList.value = selectableDeptLisBack.value;
    }
  };
  // 选中用户
  const userChecked = (id: any) => {
    userOfCurrentDept.value?.forEach((e: any) => {
      e.checked = false;
      if (e.id === id) {
        e.checked = true;
        emit('update:user', e);
      }
    });
  };
  // 选中部门
  const deptChecked = (id: any) => {
    if (props.type === 'user') {
      return;
    }
    selectableDeptList.value?.forEach((e: any) => {
      e.checked = false;
      if (e.id === id) {
        e.checked = true;
        emit('update:user', e);
      }
    });
  };
</script>

<style lang="less" scoped>
  .search {
    margin-bottom: 16px;

    .user-search {
      background-color: #ffff;
      border: 1px solid #cad0db;
      border-radius: 4px;
    }
  }

  .breadcrumb-box {
    margin-bottom: 16px;

    .dept-label {
      height: 22px;
      color: #828b9b;
      font-weight: 400;
      font-size: 14px;
      line-height: 22px;
      cursor: pointer;
    }

    .arco-breadcrumb-item:last-child .dept-label {
      color: #1e2228;
    }
  }

  .spin-box {
    width: 100%;
  }

  .dept-item-box {
    .item {
      display: flex;
      align-content: center;
      justify-content: space-between;
      align-items: center;
      height: 48px;
      padding: 0 8px;
      .left {
        display: flex;
        align-content: center;
      }

      .dept-icon {
        display: flex;
        flex-wrap: wrap;
        align-content: center;
        justify-content: center;
        width: 32px;
        height: 32px;
        margin-right: 8px;
        background: #f0f5ff;
        border-radius: 8px;

        img {
          width: 15px;
          height: 15px;
          background-repeat: no-repeat;
          background-position: center;
          background-size: cover;
        }
      }

      .label-text {
        height: 22px;
        padding: 5px 0;
        color: #1e2228;
        font-weight: 400;
        font-size: 14px;
        line-height: 22px;
        text-align: left;

        .user-num {
          height: 22px;
          color: #828b9b;
          line-height: 22px;
          text-align: left;
        }
      }

      .opt {
        color: #1e89ff;
        font-weight: 400;
        font-size: 14px;
        cursor: pointer;
      }
      &:hover {
        background: #ebf4ff;
        border-radius: 6px;
      }
    }
    .item.check {
      background: #ebf4ff;
      border-radius: 6px;
    }
  }

  .user-item-box {
    .item {
      display: flex;
      align-content: center;
      padding: 8px;

      .user-icon {
        width: 32px;
        height: 32px;
        margin-right: 8px;
        font-size: 12px;
        line-height: 32px;
        text-align: center;
        border-radius: 8px;
      }

      .label-text {
        height: 22px;
        padding: 5px 0;
        color: #1e2228;
        font-weight: 400;
        font-size: 14px;
        line-height: 22px;
        text-align: left;
      }

      &:hover {
        background: #ebf4ff;
        border-radius: 6px;
      }
    }

    .item.check {
      background: #ebf4ff;
      border-radius: 6px;
    }
  }
</style>
